#include "WebRtcServer.h"
#include "utils.h"
#include "TransportTuple.h"
#include "WebRtcTransport.h"

WebRtcServer::WebRtcServer(const std::string& id):id(id) {

    std::string ip = "0.0.0.0";

    Utils::IP::NormalizeIp(ip);

    SocketFlags flags;
    flags.ipv6Only = false; // Set to true if you want to bind to IPv6 only
    flags.udpReusePort = true; // Set to true if you want

    UdpSocket *udpSocket;
    udpSocket = new UdpSocket(this, ip, 35400, flags);

    this->udpSocketOrTcpServers.emplace_back(udpSocket, nullptr, ip, false);
}

WebRtcServer::~WebRtcServer() {
    this->closing = true;

    for (auto& item : this->udpSocketOrTcpServers) {
        delete item.udpSocket;
        item.udpSocket = nullptr;
    }
    this->udpSocketOrTcpServers.clear();
}

inline void WebRtcServer::OnUdpSocketPacketReceived(UdpSocket *socket, const uint8_t* data, size_t len,
                                           const struct sockaddr* addr) {
    TransportTuple tuple(socket, addr);
    OnPacketReceived(&tuple, data, len);
}

inline void WebRtcServer::OnPacketReceived(TransportTuple *tuple, const uint8_t* data, size_t len) {
    // Stun协议的内容也在这里
    OnNonStunDataReceived(tuple, data, len);
}

void WebRtcServer::OnNonStunDataReceived(TransportTuple *tuple, const uint8_t* data, size_t len) {
    auto it = this->mapTupleWebRtcTransport.find(tuple->hash);

	if (it == this->mapTupleWebRtcTransport.end()) {
		return;
	}

	auto* webRtcTransport = it->second;
    webRtcTransport->ProcessNonStunPacketFromWebRtcServer(tuple, data, len);
}